package com.demo.controller;

import com.demo.dao.FanweiDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/fan")
public class FanweiController {

    @Autowired
    private FanweiDao ruleMapper;

    @RequestMapping("/fields")
    public List<Map<Object, Object>> list(@RequestParam("fieldId") Integer fieldId){

        /**
         * 1. 从 workflow_billField 中获取字段信息
         * */
        Map<String, Object> fieldDto = ruleMapper.fieldOperates(fieldId);

        /**
         * 2. 根据字段类型，分不同的逻辑去获取数据
         * */
        if(fieldDto.get("fieldHTMLType").equals("5")){
            //2.1 下拉框
            return ruleMapper.SelectItemList(fieldId);
        }else if(fieldDto.get("fieldHTMLType").equals("3")
                && (
                fieldDto.get("type").equals(161)
                        || fieldDto.get("type").equals(162)
        )
        ){
            /**
             * 2.2 系统浏览框
             * 从 datashowset（系统浏览框按钮）中获取数据
             * key 用 datashowset.keyfield，没有的话用第一个字段
             * value 应该是用 showfield，没有我也不知道咋整，应该是除了 key 用的之后的第一个字段
             */
            String fieldShowName = ((String) fieldDto.get("fieldDBtype")).replace("browser.", "");
            Map<String, String> sqlMap = ruleMapper.findDataShowSet(fieldShowName);
            if(sqlMap != null){
                return customSelectItemList( sqlMap.get("sqltext"), sqlMap.get("keyField"), sqlMap.get("showField") );
            }

            /**
             * 2.3 从 mode_browser（自定义浏览框按钮）获取 sql
             *    value 用获取链接字段  select * from mode_custombrowserdspfield where customid = 152 and istitle = 1，应该不存在没有的情况
             * */
            sqlMap = ruleMapper.findModeBrowser(fieldShowName);
            if(sqlMap != null){
                return customSelectItemList( sqlMap.get("sqltext"), sqlMap.get("keyField"), sqlMap.get("showField") );
            }

        }

        //不知道是个啥类型
        throw new IllegalArgumentException();
    }


    private List<Map<Object,Object>> customSelectItemList(String sqlText, String keyField, String showField){
        List<Map<Object,Object>> possibleList = new ArrayList<>();
        if (sqlText == null) {
            return null;
        }
        try {
            System.out.println( "获取到的 sql：" + sqlText );
            List<Map<String, Object>> dataList = ruleMapper.findDataShow(sqlText);

            for (Map<String, Object> dataMap : dataList) {

                Map<Object,Object> wt = new HashMap<>();

                //先按照字段顺序，默认第一个字段是 key，第二个字段是 value
                int index = 1;
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    if(index == 1){
                        wt.put("selectValue", entry.getValue());
                    }else if(index == 2){
                        wt.put("selectName", splitStr(entry.getValue()));
                        //就要俩，其他不要
                        break;
                    }
                    index++;
                }

                //没明确说哪个字段，那就是第一个字段
                if(keyField != null){
                    Object o = dataMap.get(keyField);
                    if(Objects.nonNull(o)){
                        wt.put("selectValue", o);
                    }
                }

                if(showField != null){
                    Object o = dataMap.get(showField);
                    if(Objects.nonNull(o)){
                        wt.put("selectName", splitStr(o));
                    }
                }

                possibleList.add(wt);
            }
        } catch (Exception e) {
            //防一手这个 sql 有问题
            e.getStackTrace();
        }
        return possibleList;
    }

    /**
     * ~`~`7 商务标知识库管理`~`8 Government performance report`~`9 政府工作報告`~`~
     * 对于这种类型字段，要根据多语言格式过滤出来
     * */
    private String splitStr(Object o){
        String result = "";
        if(o == null){
            return result;
        }
        String regStr = "(?<=[`~`7 ])(.*?)(?=[`~`])";
        Pattern compile = Pattern.compile(regStr);
        Matcher matcher = compile.matcher(o.toString());
        while (matcher.find()){
            return matcher.group(0);
        }
        return o.toString();
    }
}
